const init = require('./init')
const express = require('express')
const RED = require('node-red')
const http = require('http')
const cookies = require('cookie-parser')
const { redSettings, commonSettings } = require('./userSettings')
const middleware = require('./middleware')
const routes = require('./routes')

const app = express()
// 引入静态资源
app.use('/static', express.static('public'))

// 引入模板引擎
app.engine('html', require('express-art-template'))
// 模板引擎的选项
app.set('views', {
  debug: true
})

app.set('views', require('path').join(__dirname, 'views'))
app.set('view engine', 'art')

// 添加接收post参数的配置
// extended参数，用于控制解析数据是选择qs模块还是querystring模块 extended=true 时采用qs模块
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
// 使用 cookies
app.use(cookies())
// 引入中间件
middleware(app)
// 注册路由
routes(app)

// 创建服务器
const server = http.createServer(app)

RED.init(server, redSettings)
// red提供编辑器UI
app.use(redSettings.httpAdminRoot, RED.httpAdmin)
// // Serve the http nodes UI from /api
app.use(redSettings.httpNodeRoot, RED.httpNode)
// 处理错误
app.use(function (err, req, res, next) {
  if (err) {
    res.send('sorry,error coming...')
  }
})

app.all('*', async function (req, res) {
  await setTimeout(() => {
    res.render('404.html', {})
  }, 500)
})
// 开启服务器
server.listen(commonSettings.port, function () {
  console.log(`--------server is running on port:${commonSettings.port}--http://localhost:${commonSettings.port}/`)
})
// Start the runtime
RED.start()
